package javamobile.billsplit;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.*;

import javamobile.utils.MySocket;

import android.os.Bundle;
import android.app.Activity; 
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class FriendsActivity extends Activity {
	public static final String PREFS_NAME = "MyPrefsFile";
    
    private Button homeButton; 
    private Button createBillButton; 
    private Button pendingBillsButton; 
    private Button closedBillsButton;  
    
    private Button inviteButton; 
    
    private List<String> acceptUsernames; 
    
    private TableLayout pendingTable;  
    private TableLayout friendsTable;  
    
    View.OnClickListener homeHandler = new View.OnClickListener() {
    	@Override
    	public void onClick(View v) {
    		startActivity(new Intent(FriendsActivity.this, HomeActivity.class));   
    	}
    };  
    View.OnClickListener createBillHandler = new View.OnClickListener() {
    	public void onClick(View v) {
    		startActivity(new Intent(FriendsActivity.this, CreateBillActivity.class)); 
    	}
    };  
    View.OnClickListener pendingBillsHandler = new View.OnClickListener() {
    	public void onClick(View v) {
    		startActivity(new Intent(FriendsActivity.this, PendingBillsActivity.class)); 
    	}
    };  
    View.OnClickListener closedBillsHandler = new View.OnClickListener() {
    	public void onClick(View v) {
    		startActivity(new Intent(FriendsActivity.this, ClosedBillsActivity.class)); 
    	}
    };  
	
    View.OnClickListener inviteHandler = new View.OnClickListener() {
    	@SuppressWarnings("unchecked")
		public void onClick(View v) { 
    		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            String username = settings.getString("username", "DEFAULT");
            Map<String, Object> input = new HashMap<String, Object>(); 
            input.put("username", username); 
            input.put("action",  "invite.do");  
            EditText inviteField = (EditText) findViewById(R.id.invite_field_FRIENDS); 
            String email = inviteField.getText().toString();   
            input.put("email", email);   
            List<String> inputErrors = new ArrayList<String>();  
        	if(email.equals(""))
            	inputErrors.add("Username is required for inviting a friend"); 
            if(inputErrors.size() != 0) { 
            	Intent toError = new Intent(FriendsActivity.this, ErrorActivity.class);
            	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(inputErrors)); 
            	startActivity(toError); 
            	return; 
            }
            Map<String, Object> output;  
            try {
            	output = MySocket.runSocket(input); 
            	List<String> errors = (List<String>) output.get("errors");
        	    if (errors.size()!=0) {
        	    	Intent toError = new Intent(FriendsActivity.this, ErrorActivity.class);
        	    	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(errors)); 
        	    	startActivity(toError); 
        	    } else {
        	    	Intent toFriends = new Intent(FriendsActivity.this, FriendsActivity.class); 
        	    	startActivity(toFriends); 
        	    	finish(); 
        	    }
            } catch (UnknownHostException e) {
    			System.out.println("UnknownHostException");
    			e.printStackTrace();
    		} catch (IOException e) {
    			System.out.println("IOException");
    			e.printStackTrace();
    		} catch (ClassNotFoundException e) {
    			System.out.println("ClassNotFoundException");
    			e.printStackTrace();
    		}
    	}
    };  
    
    /*View.OnClickListener acceptHandler = new View.OnClickListener() {
    	public void onClick(View v) {
    		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            String username = settings.getString("username", "DEFAULT");
            Map<String, Object> input = new HashMap<String, Object>(); 
            input.put("username", username); 
            input.put("action",  "accept.do");  
            EditText inviteField = (EditText) findViewById(R.id.invite_field_FRIENDS); 
            String email = inviteField.getText().toString();   
            input.put("email", email);   
            List<String> inputErrors = new ArrayList<String>();  
        	
    	}
    }; */   
    
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friends_main);
        
        // Setup bottom buttons
        homeButton = (Button) findViewById(R.id.home_button_FRIENDS); 
        createBillButton = (Button) findViewById(R.id.create_bill_button_FRIENDS); 
        pendingBillsButton = (Button) findViewById(R.id.pending_bills_button_FRIENDS); 
        closedBillsButton = (Button) findViewById(R.id.closed_bills_button_FRIENDS); 
        homeButton.setOnClickListener(homeHandler); 
        createBillButton.setOnClickListener(createBillHandler);   
        pendingBillsButton.setOnClickListener(pendingBillsHandler); 
        closedBillsButton.setOnClickListener(closedBillsHandler); 
        
        // Get info from server
        Map<String, Object> input = new HashMap<String, Object>(); 
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String username = settings.getString("username", "DEFAULT");
        input.put("username", username); 
        input.put("action",  "friends.do");  
        Map<String, Object> output;  
        Map<String, String> friendsList = null; 
        Map<String, String> pendingList = null; 
        try {
        	output = MySocket.runSocket(input); 
            friendsList = (Map<String, String>) output.get("friend"); 
            pendingList = (Map<String, String>) output.get("pending"); 
        } catch (UnknownHostException e) {
			System.out.println("UnknownHostException");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IOException");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("ClassNotFoundException");
			e.printStackTrace();
		}
        
        // Setup friends list
        pendingTable = (TableLayout) findViewById(R.id.pending_TABLE_FRIENDS); 
        acceptUsernames = new ArrayList<String>(); 
        int i = 0;    
        for(String key: pendingList.keySet()) {
        	String[] splitting = key.split(":"); 
        	String pendingUserNameStr = splitting[0]; 
        	String pendingNameStr = ""; 
        	if(splitting.length > 1)
        		pendingNameStr = splitting[1];    
        	String pendingStatusStr = pendingList.get(key); 
        	TextView pendingUserName = new TextView(this);  
        	pendingUserName.setText(pendingUserNameStr+"  "); 
        	TextView pendingName = new TextView(this);   
        	pendingName.setText(pendingNameStr+"  ");    
   
        	Button pendingStatusButton = null; 
        	TextView pendingStatus = null; 
    		if(pendingStatusStr.equals("Received")) { 
        		pendingStatusButton = new Button(this); 
        		pendingStatusButton.setGravity(17);   
        		pendingStatusButton.setText("Accept"); 
        		acceptUsernames.add(pendingUserNameStr); 
        		pendingStatusButton.setId(i++); 
        	    pendingStatusButton.setOnClickListener(
        	    		new View.OnClickListener() {
        	    	    	public void onClick(View v) {
        	    	    		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        	    	            String username = settings.getString("username", "DEFAULT");
        	    	            Map<String, Object> input = new HashMap<String, Object>(); 
        	    	            input.put("username", username); 
        	    	            input.put("action",  "accept.do");  
        	    	            String email = acceptUsernames.get(v.getId());  
        	    	    		input.put("email", email);   
        	    	            Map<String, Object> output;  
        	    	            try {
        	    	            	output = MySocket.runSocket(input); 
        	    	            	List<String> errors = (List<String>) output.get("errors");
        	    	        	    if (errors.size()!=0) {
        	    	        	    	Intent toError = new Intent(FriendsActivity.this, ErrorActivity.class);
        	    	        	    	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(errors)); 
        	    	        	    	startActivity(toError); 
        	    	        	    } else {
        	    	        	    	Intent toFriends = new Intent(FriendsActivity.this, FriendsActivity.class); 
        	    	        	    	startActivity(toFriends); 
        	    	        	    	finish(); 
        	    	        	    }
        	    	            } catch (UnknownHostException e) {
        	    	    			System.out.println("UnknownHostException");
        	    	    			e.printStackTrace();
        	    	    		} catch (IOException e) {
        	    	    			System.out.println("IOException");
        	    	    			e.printStackTrace();
        	    	    		} catch (ClassNotFoundException e) {
        	    	    			System.out.println("ClassNotFoundException");
        	    	    			e.printStackTrace();
        	    	    		}
        	    	    	}
        	    		});    
    		} else if(pendingStatusStr.equals("Sent")) {
    			pendingStatus = new TextView(this); 
    			pendingStatus.setText("Invite Sent"); 
    		}
    		TableRow tr = new TableRow(this);        
        	tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,   
                LayoutParams.WRAP_CONTENT));  
        	tr.addView(pendingUserName);     
        	tr.addView(pendingName);   
        	if(pendingStatusStr.equals("Received"))   
        		tr.addView(pendingStatusButton); 
        	else if(pendingStatusStr.equals("Sent"))
        		tr.addView(pendingStatus); 
        	pendingTable.addView(tr); 
        }
        
        // Setup friends list
        friendsTable = (TableLayout) findViewById(R.id.friends_TABLE_FRIENDS); 
        for(String key: friendsList.keySet()) {
        	TextView friendUserName = new TextView(this);  
        	friendUserName.setText(key); 
        	TextView friendName = new TextView(this);  
        	friendName.setText(friendsList.get(key));  
        	TableRow tr = new TableRow(this);   
        	tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,   
                LayoutParams.WRAP_CONTENT));  
        	tr.addView(friendUserName);     
        	tr.addView(friendName);   
        	friendsTable.addView(tr); 
        }

        inviteButton = (Button) findViewById(R.id.invite_button_FRIENDS); 
        inviteButton.setOnClickListener(inviteHandler); 
        
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.friends_main, menu);
        return true; 
    }
}
